package com.zxc.oj.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.zxc.oj.ojcodesandbox.model.ExecuteCodeRequest;
import com.zxc.oj.ojcodesandbox.model.ExecuteCodeResponse;
import com.zxc.oj.ojcodesandbox.model.ExecuteMessage;
import com.zxc.oj.ojcodesandbox.model.JudgeInfo;
import com.zxc.oj.ojcodesandbox.utils.ProcessUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


public abstract class JavaCodeSandboxTemple implements CodeSandbox {
    private final static String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private final static String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private final static Long TIME_OUT = 1000L;
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String language = request.getLanguage();
        String code = request.getCode();
        //把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);
        //编译代码，得到class文件
        ExecuteMessage executeMessage = compileFile(userCodeFile);
        System.out.println(executeMessage);
        //运行
        List<ExecuteMessage> executeMessages = run(userCodeFile, inputList);
        //删除用户文件
        delFile(userCodeFile);
        //封装响应
        return getOutputResponse(executeMessages);
    }

    /**
     * 把用户的代码保存为文件
     * @param code 用户代码
     * @return 用户文件
     */
    public File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断目录是否存在，不存在则创建目录
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }

    /**
     * 编译用户代码
     * @param userCodeFile 用户代码文件
     * @return 执行消息
     */
    public ExecuteMessage compileFile(File userCodeFile) {
        String compileCmd = String.format("javac -encoding utf-8 -source 1.8 -target 1.8 %s", userCodeFile.getAbsolutePath());
        try {
            Process process = Runtime.getRuntime().exec(compileCmd);
            //等待程序执行获取错误码
            ExecuteMessage executeMessage = ProcessUtils.ProcessExecuteMessage(process, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译失败");
            }
            System.out.println("executeMessage:" + executeMessage);
            return executeMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 运行用户程序
     * @param inputList 测试用例
     * @return 执行消息集合
     */
    public List<ExecuteMessage> run(File userCodeFile, List<String> inputList) {
        File userCodeParentPath = userCodeFile.getParentFile();
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String executeCmd = String.format("java -Xmx256m -Dfile.encoding=utf-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                Process process = Runtime.getRuntime().exec(executeCmd);
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        if (process.isAlive()) {
                            process.destroy();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
                //等待程序执行获取错误码
                ExecuteMessage executeErrorMessage = ProcessUtils.ProcessExecuteMessage(process, "运行");
                System.out.println("executeErrorMessage:" + executeErrorMessage);
                executeMessageList.add(executeErrorMessage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return executeMessageList;
    }

    /**
     * 封装响应
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();

        List<String> outputList = new ArrayList<>();

        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {

            String errorMessage = executeMessage.getErrorMessage();

            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                //3 表示用户代码编译错误
                response.setStatus(3);
                break;
            }
            Long runTime = executeMessage.getRunTime();
            if (ObjectUtil.isNotEmpty(runTime)) {
                maxTime = Math.max(maxTime, runTime);
            }

            outputList.add(executeMessage.getMessage());
        }
        response.setOutputList(outputList);
        if (outputList.size() == executeMessageList.size()) {
            //1 表示用户代码运行正常
            response.setStatus(1);
        }
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        response.setJudgeInfo(judgeInfo);
        return response;
    }

    /**
     * 删除用户文件
     * @return
     */
    public boolean delFile(File userCodeFile) {
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }


    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        //2 表示代码沙箱运行错误
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());

        return response;
    }
}
